package school.emm;
 
import java.io.IOException;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.ericsson.mmaps.CustomLayer;
import com.ericsson.mmaps.FontProvider;
import com.ericsson.mmaps.GeoMap;
import com.ericsson.mmaps.MapComponent;
import com.ericsson.mmaps.MapFactory;
import com.ericsson.mmaps.MapStyle;
import com.ericsson.mmaps.MapView;
import com.ericsson.mmaps.PickListener;
import com.ericsson.mmaps.SymbolProvider;
import com.ericsson.mmaps.graphics.RaveGeoFont;
import com.ericsson.mmaps.graphics.RaveGeoImage;
import com.ericsson.mmaps.tools.CoordinateTool;
import com.ericsson.mmaps.tools.KeyNavigationTool;
import com.ericsson.mmaps.tools.ScaleBarTool;
import com.ericsson.mmaps.tools.TouchNavigationTool;
 
public class MyFirstEmmActivity extends Activity {
	private MyListener listener = null;
	private CustomLayer customLayer_;
	private MapView mapView_ = null;
	private CommunicateWithServer comThread_;
	private int chatroomSlots_ = 3;
	private boolean registered_ = false;
	private ChatRoomSymbol[] currentChatrooms_ = new ChatRoomSymbol[chatroomSlots_];
	private static final String DATABASE_KEY = "8gwRRmZs9yovncPOKjA4JeGBqxGy2XckjM6FAs1r";
	
	//Request codes
	protected final int CONNECT_ = 0;
	protected final int CREATECR_ = 1;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        MapStyle style = new MapStyle();
        
        // Set the style below to use Open Street Maps.
        style.set(MapStyle.MAP_SOURCE, MapStyle.OPEN_STREET_MAP);

        MapFactory factory = MapFactory.getInstance();

        try {
			mapView_ = factory.createMapView(this, style, fonts(), symbols(), DATABASE_KEY);
		} catch (Exception e) {
			e.printStackTrace();
		}

		RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.mainlayout);
		mapView_.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		mainLayout.addView(mapView_,0);
		
		// -------------------- ZOOM -------------------------
		final ZoomControls zoomControls_ = (ZoomControls) findViewById(R.id.zoomControls);
		zoomControls_.setOnZoomInClickListener(new OnClickListener() {
	
			public void onClick(View arg0) {
				GeoMap map = mapView_.getMapComponent().getMap();
				int targetScale = (int)((map.getScale() * (long)20) / 100);
				map.setScale(targetScale);
				mapView_.getMapComponent().repaint();
				
				zoomControls_.setIsZoomOutEnabled(true);
				if (map.getScale() == map.getMinScale())
					zoomControls_.setIsZoomInEnabled(false);
			}
		});
		zoomControls_.setOnZoomOutClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				GeoMap map = mapView_.getMapComponent().getMap();
				int targetScale = (int)((map.getScale() * 100L) / 20);
				map.setScale(targetScale);
				mapView_.getMapComponent().repaint();
				
				zoomControls_.setIsZoomInEnabled(true);
				if (map.getScale() == map.getMaxScale())
					zoomControls_.setIsZoomOutEnabled(false);
			}
		});

		// ------------------ END ZOOM -----------------------
		
		// -------------------- TOOLS ------------------------

		TouchNavigationTool touchController = new UIEventHandler(getBaseContext(), mapView_, true, this);
		touchController.activate();
		touchController.setPickListener((PickListener) touchController);
		
		KeyNavigationTool keyController = new KeyNavigationTool((MapComponent) mapView_.getMapComponent(), false);
        keyController.activate();

		mapView_.getMapComponent().addTool(new ScaleBarTool(mapView_.getMapComponent()));
		mapView_.getMapComponent().addTool(new CoordinateTool(mapView_.getMapComponent().getMap()));

		// ------------------ END TOOLS ----------------------
		
		// ------------------- CUSTOM LAYER ------------------
		customLayer_ = new CustomLayer();
		mapView_.getMap().addLayer(customLayer_);

        // --------------- END CUSTOM LAYER-------------------
		
		
		if(registered_ == false) {
			Intent register = new Intent(this, LoginActivity.class);
			startActivityForResult(register, CONNECT_);
		}
		
		
    }

	
    
    @Override
    public void onStart()
    {
    	super.onStart();    	
    }
    @Override
    public void onResume()
    {
    	super.onResume();
    	listener = new MyListener();
        registerReceiver(listener, new IntentFilter("school.emm.ec.SEND_MESSAGE"));
    }
    
    @Override
    public void onPause()
    {
    	super.onPause();
    	 if (listener != null){
             unregisterReceiver(listener);
             listener = null;
         }
    	
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        // This is our one standard application action -- inserting a
        // new note into the list.
        menu.add("Locate Me")
                .setShortcut('3', 'a')
                .setIcon(android.R.drawable.ic_menu_compass);

        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        	case 0:
        	{
        		Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_COARSE);
                criteria.setAltitudeRequired(false);
                criteria.setBearingRequired(false);
                criteria.setCostAllowed(true);
                criteria.setPowerRequirement(Criteria.POWER_LOW);

                LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
                
                String provider = locationManager.getBestProvider(criteria, true);
                if (provider == null) {
                	Toast.makeText(this, "Couldn't get a location provider", Toast.LENGTH_SHORT);
                	return super.onOptionsItemSelected(item);
                }
                Location location = locationManager.getLastKnownLocation(provider);
                
                mapView_.getMap().setGeoCenterY(location.getLatitude());
                mapView_.getMap().setGeoCenterX(location.getLongitude());
        	}
        }
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    public void onDestroy()
    {
    	super.onDestroy();
    	if (mapView_ != null) mapView_.close();
        MapFactory.getInstance().close();
    }
    
    protected final FontProvider fonts() {
        return new FontProvider() {
            public RaveGeoFont medium() {
                return new RaveGeoFont(Typeface.DEFAULT, 12);
            }

            public RaveGeoFont mediumBold() {
                return new RaveGeoFont(Typeface.DEFAULT_BOLD, 12);
            }

            public RaveGeoFont small() {
                return new RaveGeoFont(Typeface.DEFAULT, 10);
            }

            public RaveGeoFont smallBold() {
                return new RaveGeoFont(Typeface.DEFAULT_BOLD, 10);
            }

            public RaveGeoFont smallItalic() {
                return new RaveGeoFont(Typeface.create(Typeface.DEFAULT, Typeface.ITALIC), 10);                
            }            
        };
    }
    
    protected final SymbolProvider symbols() {
        return new SymbolProvider() {
            
            private RaveGeoImage airport = null;
			private RaveGeoImage subway = null;
			private RaveGeoImage railway = null;
			private RaveGeoImage ferry = null;
			private RaveGeoImage poi = null;
			private RaveGeoImage city = null;
			private RaveGeoImage bus = null;

			public boolean hasSymbols() {
                return true;
            }

            public RaveGeoImage airport() throws IOException {
            	if(airport == null) {
            		airport = RaveGeoImage.createImage(getResources().getDrawable(R.drawable.plane));	
            	}
                return airport;
            }

            public RaveGeoImage bus() throws IOException {
            	if(bus == null) {
            		bus = RaveGeoImage.createImage(getResources().getDrawable(R.drawable.pstop));
            	}
            	return bus;
            }

            public RaveGeoImage city() throws IOException {
            	if(city == null) {
            		city = RaveGeoImage.createImage(getResources().getDrawable(R.drawable.reddot));
            	}
            	return city;
            }

            public RaveGeoImage defaultPoi() throws IOException {
            	if(poi == null) {
            		poi = RaveGeoImage.createImage(getResources().getDrawable(R.drawable.smallsquare));
            	}
            	return poi;
            }

            public RaveGeoImage ferry() throws IOException {
            	if(ferry == null) {
            		ferry = RaveGeoImage.createImage(getResources().getDrawable(R.drawable.ferry));
            	}
            	return ferry;
            }

            public RaveGeoImage railway() throws IOException {
            	if(railway == null) {
            		railway = RaveGeoImage.createImage(getResources().getDrawable(R.drawable.train));
            	}
            	return railway;
            }

            public RaveGeoImage subway() throws IOException {
            	if(subway == null) {
            		subway = RaveGeoImage.createImage(getResources().getDrawable(R.drawable.t));	
            	}
                return subway;
            }
        };
    }
	public void createChatRoomOnMap(String topic, int categoryID, int x, int y, int chatId){
		ChatRoomSymbol chatroom = new ChatRoomSymbol(x, y, RaveGeoImage.createImage(getBaseContext().getResources().getDrawable(R.drawable.icon)));
		chatroom.setTopic(topic);
		chatroom.setCategory(categoryID);
		customLayer_.add(chatroom);
		mapView_.refresh();
		if (chatId == -1) {
			addChatroomToList(chatroom);	
		} else {
			setChatId(chatId);
		}
		
    }
	
	public void recievedChatMessage(String msg) {
		System.out.println("Recieved");
	    Intent i = new Intent();
	    i.setAction("school.emm.ec.NEW_MESSAGE");
	    i.putExtra("message", msg);
	    
	    sendBroadcast(i);
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch(requestCode) {
		case CONNECT_:
			if (resultCode == RESULT_OK){
				comThread_ = new CommunicateWithServer(data.getStringExtra("nickname"), this);
				registered_ = true;
			}
			break;
		case CREATECR_:
			if (resultCode == RESULT_OK) {
	    		Bundle result = new Bundle();
	        	result = data.getExtras();
	        	String topic = result.getString("topic");
	        	int category = result.getInt("category");
	        	int x = result.getInt("X");
	        	int y = result.getInt("Y");
	        	createChatRoomOnMap(topic, category, x, y, -1);
	            System.out.println(topic+"\n"+category+"\n"+x+"\n"+y);
	            comThread_.createChatRoomToServer("2", comThread_.getProtocol().getUserid(), category, topic, x, y);
	    	}
		}
    	
    }
	
	public int getChatroomSlots() {
		return this.chatroomSlots_;
	}
	
	private void addChatroomToList(ChatRoomSymbol room) {
		for(int i = 0; i < currentChatrooms_.length; i++) {
			if(currentChatrooms_[i] == null) {
				currentChatrooms_[i] = room;
				decChatroomSlot();
				break;
			}
		}
	}
	
	private void removeChatroomFromList(int chatId) {
		for (int i = 0; i < currentChatrooms_.length; i++) {
			if (currentChatrooms_[i].getChatId() == chatId) {
				int j;
				for (j = currentChatrooms_.length - i; j < currentChatrooms_.length-1; j++) {
					currentChatrooms_[j] = currentChatrooms_[j+1];
				}
				currentChatrooms_[j] = null;
				incChatroomSlot();
				break;
			}
		}
	}
	
	private void incChatroomSlot(){
		this.chatroomSlots_++;
	}
	private void decChatroomSlot(){
		this.chatroomSlots_--;
	}
	public void setChatId(int id){
		for (int i = 0; i < currentChatrooms_.length; i++) {
			if (currentChatrooms_[i].getChatId() == -1) {
				currentChatrooms_[i].setChatId(id);
				break;
			}
		}
	}
	public void joinChatroom(int chatroomid) {
		comThread_.sendMessageToServer("3" + ";" + chatroomid + ";" + comThread_.getProtocol().getUserid());
	}
	
    protected class MyListener extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // No need to check for the action unless the listener will
            // will handle more than one - let's do it anyway
            if (intent.getAction().equals("school.emm.ec.SEND_MESSAGE")) {
            	System.out.println("1"+ ";" + currentChatrooms_[0].getChatId() + ";" + comThread_.getProtocol().getUserid() + ";" + intent.getStringExtra("message"));
                comThread_.sendMessageToServer("1"+ ";" + currentChatrooms_[0].getChatId() + ";" + comThread_.getProtocol().getUserid() + ";" + intent.getStringExtra("message"));
            }
        }
    }
}
